#!/sbin/openrc-run

# script to start raid devices described in /etc/mdadm.conf.
depend() {
	before checkfs fsck swap
	after modules
}

array_devices() {
	awk '/^ARRAY/ {print $2}' /etc/mdadm.conf
}

start() {
	[ -f /etc/mdadm.conf ] || return 0
	# start all devices that are not already started
	[ -f /proc/mdstat ] || modprobe md > /dev/null 2>&1
	local tostart=
	for i in $(array_devices); do
		[ -b "$i" ] && continue
		tostart="$tostart $i"
	done
	[ -z "$tostart" ] && return 0

	ebegin "Starting RAID devices"
	mdadm --assemble --scan --quiet $tostart
	eend $?
}

is_mounted_as() {
	local mnt
	for mnt in $(lsblk -o MOUNTPOINT $1); do
		[ "$mnt" = "$2" ] && return 0
	done
	return 1
}

stop() {
	# stop all raid devices except anything mounted as /
	[ -f /etc/mdadm.conf ] || return 0
	ebegin "Stopping RAID devices"
	local tostop=
	for i in $(array_devices); do
		is_mounted_as $i / && continue
		tostop="$tostop $i"
	done
	mdadm --stop --quiet $tostop
	eend $?
}
